//
//  AppDelegate.m
//  pickpic
//
//  Created by GaoYongyue on 16/8/12.
//  Copyright © 2016年 高老师很忙. All rights reserved.
//

#import "AppDelegate.h"

#import "PPFeatureGuideViewController.h"
#import "PPLoginNavigationController.h"
#import "PPLoginViewController.h"

#import "PPHomeNavigationController.h"
#import "PPHomeViewController.h"

#import "PPResourceManager.h"

#import "PPSocializationManager.h"

#import "PPLoginAndRegisterViewController.h"
static NSString *const kUMAPPKey = @"57a307d1e0f55a33f9001c01";

#import "PPHomeRootViewController.h"

#define isFirstSartApp @"ifFirst"
@interface AppDelegate ()
@property (nonatomic,strong) PPBaseNavigationViewController *navigationController;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[PPResourceManager sharedInstance] launchWithOptions:launchOptions];

    return YES;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [[PPNetworkManager sharedInstance] checkNetworkStatusChangeBlock:nil];
    
    //注册fonts目录下面的所有字体文件
    [[PPUserAccount currentUser] registerFont];
    
    //注册远程推送
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound) categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    [[UIApplication sharedApplication] registerForRemoteNotifications];


    //statu bar
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
    //友盟
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];

    [MobClick setEncryptEnabled:YES];

    UMConfigInstance.appKey = kUMAPPKey;
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];

    
    
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:kTemplatePlist];
    
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:kTemplatePlist]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:isFirstSartApp];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    if (blHave && ![[[NSUserDefaults standardUserDefaults] objectForKey:isFirstSartApp] boolValue]) {

        [[NSFileManager defaultManager] removeItemAtPath:kTemplatePlist error:nil];
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:isFirstSartApp];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    //设置状态栏字体颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];

    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.backgroundColor = [UIColor whiteColor];
    [_window makeKeyAndVisible];

    
    NSString *key = (NSString *)kCFBundleVersionKey;
    NSString *lastVersionCode = [[NSUserDefaults standardUserDefaults] objectForKey:key];
    //加载程序中info.plist文件(获得当前软件的版本号)
    NSString *currentVersionCode = [NSBundle mainBundle].infoDictionary[key];
    if ([lastVersionCode isEqualToString:currentVersionCode]) {
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
        // 非第一次使用软件
        // 2.3.开始
        if ([[PPAccountManager sharedInstance].account validateAccount]) {
            PPHomeViewController *homeViewController = [[PPHomeViewController alloc] init];
            homeViewController.launchedByNotification = ([launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey] != nil);
            self.navigationController = [[PPBaseNavigationViewController alloc] initWithRootViewController:homeViewController];
            _window.rootViewController = self.navigationController;
        }else{
            PPLoginAndRegisterViewController *loginRegister = [[PPLoginAndRegisterViewController alloc] init];
            self.navigationController = [[PPBaseNavigationViewController alloc] initWithRootViewController:loginRegister];
            _window.rootViewController = self.navigationController;
        }

    } else {
            [[UIApplication sharedApplication] setStatusBarHidden:YES];
        // 第一次使用软件
        // 保存当前软件版本号
        [[NSUserDefaults standardUserDefaults] setObject:currentVersionCode forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
        //启动页控制器
        PPFeatureGuideViewController *guideViewController = [[PPFeatureGuideViewController alloc] init];
        _window.rootViewController = guideViewController;
    }
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [[PPSocializationManager sharedInstance] handleOpenURL:url];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

//        UILocalNotification *n = [[UILocalNotification alloc] init];
//        n.fireDate = [NSDate date];
//        n.alertBody = @"test body";
//        [application scheduleLocalNotification:n];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {

    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
    [[SDImageCache sharedImageCache] clearDisk];
    
    [[SDImageCache sharedImageCache] clearMemory];//可有可无
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [deviceToken description];

    if(token == nil) {
        return;
    }

    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"DeviceToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//iOS8
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    // 注册远程通知
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //    NSLog(@"得到的设备令牌 失败%@",error);
}


- (BOOL)application:(UIApplication *)app openURL:(nonnull NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(nonnull id)annotation {
    return [[PPSocializationManager sharedInstance] handleOpenURL:url];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo {
    BOOL isActive = [application applicationState] == UIApplicationStateActive;

    if(!isActive) {
        UIViewController *rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;

        if([rootViewController isKindOfClass:[UINavigationController class]]) {
            UINavigationController *navigationController = (UINavigationController *)rootViewController;

            PPHomeViewController *homeViewController = navigationController.viewControllers.firstObject;

            void (^action) (void) = ^{
                if(homeViewController.state == PPHomeViewStateDashboard) {
                    [navigationController popToRootViewControllerAnimated:NO];
                } else {
                    [homeViewController toggleState:PPHomeViewStateDashboard animated:NO completion:^{
                        [navigationController popToRootViewControllerAnimated:NO];
                    }];
                }
            };

            if(rootViewController.presentedViewController != nil) {
                [rootViewController dismissViewControllerAnimated:NO completion:^{
                    action();
                }];
            } else {
                action();
            }
        }

        //        NSString *alert = [[nofitfication validDictionaryForKey:@"aps"] validStringForKey:@"alert"];
        //        if ([alert length])
        //        {
        //            UIAlertController *alertControler = [UIAlertController alertControllerWithTitle:@"新消息" message:alert preferredStyle:UIAlertControllerStyleAlert];
        //            [alertControler addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //
        //            }]];
        //            [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:alertControler animated:YES completion:nil];
        //        }
    }
}

@end
